<template>
  <!--  <h2>阶段模板设置</h2>-->
    <div class="app-container">
      <el-row :gutter="20">
        <el-col :span="4" :xs="24">
          <el-row ref="hMain">
            <el-col :span="24">
              <div class="head-container">
                <el-input v-model="nodeName" placeholder="请输入名称" clearable size="small" prefix-icon="el-icon-search"
                          style="margin-bottom: 20px" />
              </div>
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button type="primary" plain icon="el-icon-plus" size="small"
                             @click="treeHandleAdd">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="success" plain icon="el-icon-edit" size="small"
                             @click="treeHandleUpdate">修改</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="danger" plain icon="el-icon-delete" size="small"
                             @click="treeHandleDelete">删除</el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

          <div class="head-container" :style="{height:treeHeight+'px'}" style="overflow: auto">
            <el-tree :data="stageOptions" :props="defaultProps" :expand-on-click-node="false"
                     :filter-node-method="filterNode" :default-expanded-keys="expandedkeys"
                     :current-node-key="currentNodekey" ref="tree" node-key="phaseId" default-expand-all highlight-current
                     @node-click="handleNodeClick" :style="size">
              <template slot-scope="{ node, data }">
                <span class="span-ellipsis" :title="node.label" :style="size">{{ node.label }}</span>
              </template>
            </el-tree>
          </div>
        </el-col>

        <el-col :span="20" :xs="24" v-show="isShow">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                   label-width="68px">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable style="width: 240px"
                        @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row :gutter="10" class="mb8" ref="refbut">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus"  @click="handleAdd" v-hasPermi="['zt:file:save']">添加</el-button>
            </el-col>
<!--            <el-col :span="1.5">-->
<!--              <el-button type="info" plain icon="el-icon-upload2"  @click="handleImport" v-hasPermi="['zt:file:import']">导入</el-button>-->
<!--            </el-col>-->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
          <el-table v-loading="loading" :data="tableDataList" :height="tableHeight" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="fileId"/>
            <el-table-column label="文件名称" prop="fileName" align="center" />
            <el-table-column label="保管期限" prop="bgqx" align="center" />
<!--            <el-table-column label="利用控制范围" prop="isOpens" align="center" />-->
            <el-table-column label="创建时间" prop="createTime" align="center" />
            <el-table-column label="文件类型" prop="wjlx" align="center" />
            <el-table-column label="操作" align="center" width="250">
              <template slot-scope="scope">
                <el-button  type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-col>

        <el-col :span="20" :xs="24" v-show="isShowDaoru">
          <el-row :gutter="10" class="mb8" ref="refbut">
            <el-col :span="1.5">
              <el-button type="info" plain icon="el-icon-upload2"  @click="handleImport" v-hasPermi="['zt:file:import']">导入</el-button>
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="20" :xs="24" v-show="!isShow && !isShowDaoru" class="empty">
          <el-empty :image-size="200"></el-empty>
        </el-col>
      </el-row>

      <!-- 添加/修改部门节点 -->
      <el-dialog :title="departmentTitle" :visible.sync="departmentOpen" width="35%" append-to-body>
        <el-form ref="departmentForm" :model="departmentForm" :rules="departmentRules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="部门名称" prop="deptId">
                <treeselect v-model="departmentForm.deptId" :options="deptOptions" :show-count="true" placeholder="请选择" noOptionsText="暂无数据" noResultsText="暂无数据"></treeselect>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitDeptForm">保 存</el-button>
          <el-button  @click="deptCancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 添加/修改分类节点 -->
      <el-dialog :title="sortTitle" :visible.sync="sortOpen" width="35%" append-to-body>
        <el-form ref="sortForm" :model="sortForm" :rules="sortRules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="分类名称" prop="nodeName">
                <el-input v-model="sortForm.nodeName" placeholder="请输入分类名称" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitSortForm">保 存</el-button>
          <el-button  @click="sortCancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 添加/修改阶段节点 -->
      <el-dialog :title="stageTitle" :visible.sync="stageOpen" width="35%" append-to-body>
        <el-form ref="stageForm" :model="stageForm" :rules="stageRules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="阶段名称" prop="nodeName">
                <el-input v-model="stageForm.nodeName" placeholder="请输入阶段名称" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目阶段" prop="projectPhase">
                <el-select v-model="stageForm.projectPhase" clearable placeholder="请选择" style="width: 100%">
                  <el-option v-for="dict in dict.type.XMJD" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitStageForm">保 存</el-button>
          <el-button  @click="stageCancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 添加/修改文件 -->
      <el-dialog :title="fileTitle" :visible.sync="fileOpen" width="35%" append-to-body>
        <el-form ref="fileForm" :model="fileForm" :rules="fileRules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="文件名称" prop="fileName">
                <el-input v-model="fileForm.fileName" placeholder="请输入文件名称" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="保管期限" prop="bgqx">
                <el-select v-model="fileForm.bgqx" clearable placeholder="请选择" style="width: 100%">
                  <el-option v-for="dict in dict.type.BGQX" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
<!--          <el-row>-->
<!--            <el-col :span="24">-->
<!--              <el-form-item label="利用控制范围" prop="isOpens">-->
<!--                <el-select v-model="fileForm.isOpens" clearable placeholder="请选择" style="width: 100%">-->
<!--                  <el-option v-for="dict in dict.type.IS_OPENS" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>-->
<!--                </el-select>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->
          <el-row>
            <el-col :span="24">
              <el-form-item label="文件类型" prop="wjlx">
                <el-select v-model="fileForm.wjlx" clearable placeholder="请选择" style="width: 100%">
                  <el-option v-for="dict in dict.type.WJLX" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">保 存</el-button>
          <el-button  @click="fileCancel">取 消</el-button>
        </div>
      </el-dialog>

      <vimport v-if="upload.open" :upload="upload" @closeDelDialog="closeDelDialog1" :uploadData="uploadData"
               @handleFileSuccess="handleFileSuccess"></vimport>
    </div>
  </template>

  <script>
  import estimateTableHeight from '@/mixins/estimateTableHeight'//vue项目中element-tabel自动计算高度
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {deptTreeSelect} from "@/api/stage/stageManagement/itemList";
  import {
    addFile,
    addNode, deleteFile,
    deleteNode,
    getAllTree, getCodeList, getFileDetail,
    getNodeDetail, updateFile,
    updateNode
  } from "@/api/stage/stageManagement/stageTemplate";
  import vimport from '@/components/import/index.vue';
  import {getToken} from "@/utils/auth";

  export default {
    name: "index",
    mixins: [estimateTableHeight], // 混入方法
    archive_Dicts: ['BGQX', 'IS_OPENS', 'WJLX', 'XMJD'],
    components: { Treeselect, vimport },
    data() {
      return {
        // 部门名称
        nodeName: undefined,
        // 阶段模板树选项
        stageOptions: undefined,
        defaultProps: {
          children: "phasesVoList",
          label: "nodeName"
        },
        //默认展开的树节点
        expandedkeys: [],
        //默认选中的树节点
        currentNodekey: "",
        isShow: false, //是否显示右侧数据
        isShowDaoru: false, // 是否展示导入
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          fileName: undefined
        },
        // 显示搜索条件
        showSearch: true,
        // 遮挡层
        loading: true,
        // 表格数据
        tableDataList: [],
        // 总条数
        total: 0,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 弹出层标题
        fileTitle: '',
        // 是否显示弹出层
        fileOpen: false,
        // 弹出层表单
        fileForm: {
          fileName: undefined,
          bgqx: undefined,
          isOpens: undefined,
          wjlx: undefined
        },
        // 弹出层表单校验
        fileRules: {
          fileName: [
            { required: true, message: "文件名称不能为空", trigger: "blur" }
          ],
          bgqx: [
            { required: true, message: "保管期限不能为空", trigger: "blur" }
          ],
          // isOpens: [
          //   { required: true, message: "利用控制范围不能为空", trigger: "blur" }
          // ],
          wjlx: [
            { required: true, message: "文件类型不能为空", trigger: "blur" }
          ]
        },
        // 部门节点
        departmentTitle: '',
        departmentOpen: false,
        departmentForm: {
          deptId: undefined
        },
        departmentRules: {
          deptId: [
            { required: true, message: "部门名称不能为空", trigger: "blur" }
          ]
        },
        // 部门树选项
        deptOptions: [],
        // 分类节点
        sortTitle: '',
        sortOpen: false,
        sortForm: {
          nodeName: undefined
        },
        sortRules: {
          nodeName: [
            { required: true, message: "分类名称不能为空", trigger: "blur" }
          ]
        },
        // 阶段节点
        stageTitle: '',
        stageOpen: false,
        stageForm: {
          nodeName: undefined,
          projectPhase: undefined
        },
        stageRules: {
          nodeName: [
            { required: true, message: "阶段名称不能为空", trigger: "blur" }
          ],
          projectPhase: [
            { required: true, message: "项目阶段不能为空" }
          ],
        },

        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "导入文件",
          // 是否禁用上传
          isUploading: false,
          deptId: null,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/zt/file/import",
          // 下载模板的地址
          urlTemplate: "/zt/file/download/phases/file/template"
        },
        uploadData: {
          phasesId: undefined
        },
        size: ""
      }
    },
    created() {
      this.getTree();
      this.getDeptTreePost()
      if (this.$store.getters.size == 'small') {
        this.size = 'font-size: 12px;'
      } else {
        this.size = 'font-size: 14px;'
      }
    },
    watch: {
      // 根据名称筛选树
      nodeName(val) {
        this.$refs.tree.filter(val);
      },
    },
    methods: {
      // 获取树结构数据
      getTree() {
        getAllTree().then(response => {
          this.stageOptions = response.data;
          if (this.stageOptions.length > 0) {
            this.currentNodekey = this.stageOptions[0].phaseId;
            this.expandedkeys.push(this.stageOptions[0].phaseId);
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.stageOptions[0].phaseId)
            })
            if(this.stageOptions[0].nodeType == 3) {
              this.isShow = true
              this.getList()
            } else {
              this.isShow = false
            }
            if(this.stageOptions[0].nodeType == 2) {
              this.isShowDaoru = true
            } else {
              this.isShowDaoru = false
            }
            // 阶段id
            this.queryParams.phasesId = this.stageOptions[0].phaseId
            this.uploadData.phasesId = this.stageOptions[0].phaseId
            // 父级id
            this.queryParams.parentId = this.stageOptions[0].parentId
            // 节点类型
            this.queryParams.nodeType = this.stageOptions[0].nodeType
            // 节点名称
            this.queryParams.nodeName = this.stageOptions[0].nodeName
          }
        });
      },
      /** 查询部门下拉树结构 */
      getDeptTreePost() {
        deptTreeSelect().then(response => {
          this.deptOptions = response.data;
        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.nodeName.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        console.log(data)
        // 父id
        this.queryParams.parentId = data.parentId
        // 树id
        this.queryParams.phasesId = data.phaseId
        this.uploadData.phasesId = data.phaseId
          // 节点类型
        this.queryParams.nodeType = data.nodeType
        // 节点名称
        this.queryParams.nodeName = data.nodeName
        // 点击树节点时刷新查询条件
        this.resetForm("queryForm");
        if(data.nodeType == 3) {
          this.isShow = true
          this.getList()
        } else {
          this.isShow = false
        }
        if(data.nodeType == 2) {
          this.isShowDaoru = true
        } else {
          this.isShowDaoru = false
        }
      },
      // 新增树节点
      treeHandleAdd() {
        this.resetForm('departmentForm')
        this.resetForm('sortForm')
        this.resetForm('stageForm')
        if(this.queryParams.nodeType == 0) {
          this.departmentOpen = true
          this.departmentTitle = '添加'
        } else if(this.queryParams.nodeType == 1) {
          this.sortOpen = true
          this.sortTitle = '添加'
        } else if(this.queryParams.nodeType == 2) {
          this.stageOpen = true
          this.stageTitle = '添加'
        } else {
          this.$modal.msgWarning('阶段节点下不可以新增节点')
        }
      },
      // 修改树节点
      treeHandleUpdate() {
        if(this.queryParams.nodeType == 0) {
          this.$message({ message: '请选择除根节点阶段树以外的节点进行修改', type: 'warning' })
        } else {
          this.resetForm('departmentForm')
          this.resetForm('sortForm')
          this.resetForm('stageForm')
          getNodeDetail({id: this.queryParams.phasesId}).then(response=>{
            if(this.queryParams.nodeType == 1) {
              this.departmentForm = response.data
              this.departmentForm.deptId = this.getLabelName(response.data.nodeName)
              this.departmentOpen = true
              this.departmentTitle = '修改'
            } else if(this.queryParams.nodeType == 2) {
              this.sortForm = response.data
              this.sortOpen = true
              this.sortTitle = '修改'
            } else if(this.queryParams.nodeType == 3) {
              this.stageForm = response.data
              if(response.data.projectPhase != null) {
                this.stageForm.projectPhase = response.data.projectPhase.toString()
              }
              this.stageOpen = true
              this.stageTitle = '修改'
            }
          })
        }
      },
      // 根据label获取部门id回显
      getLabelName(label) {
        function recurse(nodes) {
          for (let node of nodes) {
            if(node.label == label) {
              return node.id
            }
            if (node.children) {
              const id = recurse(node.children)
              if (id) return id
            }
          }
        }
        return recurse(this.deptOptions)
      },
      // 删除树节点
      treeHandleDelete() {
        if(this.queryParams.nodeType == 0) {
          this.$message({ message: '请选择除根节点阶段树以外的节点进行删除', type: 'warning' })
        } else {
          const phaseId = this.queryParams.phasesId
          this.$modal.confirm('是否确认删除阶段名称为"' + this.queryParams.nodeName + '"的数据项？').then(function() {
            return deleteNode({id: phaseId})
          }).then(() => {
            this.getTree()
            this.isShow = false
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
        }
      },
      // 保存部门节点
      submitDeptForm() {
        console.log(this.departmentForm)
        this.$refs["departmentForm"].validate(valid => {
          if(valid) {
            if(this.departmentForm.phaseId != undefined) {
              this.departmentForm.nodeName = this.getLabelById(this.departmentForm.deptId)
              updateNode(this.departmentForm).then(response=>{
                this.$modal.msgSuccess('修改成功')
                this.departmentOpen = false
                this.getTree()
                this.isShow = false
              })
            } else {
              this.departmentForm.nodeName = this.getLabelById(this.departmentForm.deptId)
              this.departmentForm.nodeType = 1
              this.departmentForm.parentId = this.queryParams.phasesId
              addNode(this.departmentForm).then(response=>{
                this.$modal.msgSuccess('新增成功')
                this.departmentOpen = false
                this.getTree()
                this.isShow = false
              })
            }
          }
        })
      },
      // 根据id获取对应的名称
      getLabelById(id) {
        function recurse(nodes) {
          for (let node of nodes) {
            if(node.id == id) {
              return node.label
            }
            if (node.children) {
              const label = recurse(node.children)
              if (label) return label
            }
          }
        }
        return recurse(this.deptOptions)
      },
      // 取消
      deptCancel() {
        this.departmentOpen = false
      },
      // 保存分类节点
      submitSortForm() {
        this.$refs["sortForm"].validate(valid => {
          if(valid) {
            if(this.sortForm.phaseId != undefined) {
              updateNode(this.sortForm).then(response=>{
                this.$modal.msgSuccess('修改成功')
                this.sortOpen = false
                this.getTree()
                this.isShow = false
              })
            } else {
              this.sortForm.nodeType = 2
              this.sortForm.parentId = this.queryParams.phasesId
              addNode(this.sortForm).then(response=>{
                this.$modal.msgSuccess('新增成功')
                this.sortOpen = false
                this.getTree()
                this.isShow = false
              })
            }
          }
        })
      },
      // 取消
      sortCancel() {
        this.sortOpen = false
      },
      // 保存阶段节点
      submitStageForm() {
        this.$refs["stageForm"].validate(valid => {
          if(valid) {
            if(this.stageForm.phaseId != undefined) {
              updateNode(this.stageForm).then(response=>{
                this.$modal.msgSuccess('修改成功')
                this.stageOpen = false
                this.getTree()
                this.isShow = false
              })
            } else {
              this.stageForm.nodeType = 3
              this.stageForm.parentId = this.queryParams.phasesId
              addNode(this.stageForm).then(response=>{
                this.$modal.msgSuccess('新增成功')
                this.stageOpen = false
                this.getTree()
                this.isShow = false
              })
            }
          }
        })
      },
      // 取消
      stageCancel() {
        this.stageOpen = false
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery()
      },
      resetfileForm() {
        this.fileForm = {
          fileName: undefined,
          bgqx: undefined,
          isOpens: undefined,
          wjlx: undefined
        }
      },
      // 添加文件
      handleAdd() {
        this.resetForm('fileForm')
        this.resetfileForm()
        this.fileOpen = true
        this.fileTitle = '添加文件信息'
      },
      // 导入
      handleImport() {
        this.upload.open = true
      },
      //导入结果返回操作
      handleFileSuccess(response) {
        this.upload.open = false;
        this.upload.isUploading = false;
        if (response.code == "500") {
          this.$message({ message: response.msg, type: 'error' })
        } else {
          this.$modal.msgSuccess("导入成功");
          this.getTree()
        }
      },
      closeDelDialog1() {
        this.upload.open = false;
      },
      // 修改
      handleUpdate(row) {
        getFileDetail({ fileId: row.fileId }).then(response=>{
          this.fileForm = response.data
          this.fileOpen = true
          this.fileTitle = '修改文件信息'
        })
      },
      // 删除
      handleDelete(row) {
        console.log(row)
        const fileId = row.fileId
        this.$modal.confirm('是否确认删除文件名称为"' + row.fileName + '"的数据项？').then(function() {
          return deleteFile({fileId: fileId})
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      // 保存
      submitFileForm() {
        this.$refs["fileForm"].validate(valid => {
          if(valid) {
            if(this.fileForm.fileId != undefined) {
              updateFile(this.fileForm).then(response=>{
                this.$modal.msgSuccess('修改成功')
                this.fileOpen = false
                this.getList()
              })
            } else {
              this.fileForm.phasesId = this.queryParams.phasesId
              addFile(this.fileForm).then(response=>{
                this.$modal.msgSuccess('新增成功')
                this.fileOpen = false
                this.getList()
              })
            }
          }
        })
      },
      // 取消
      fileCancel() {
        this.fileOpen = false
      },
      // 查询列表
      getList() {
        this.loading = true
        getCodeList(this.queryParams).then(response=>{
          this.loading = false
          this.tableDataList = response.rows
          for (let i = 0; i < response.rows.length; i++) {
            for (let j = 0; j < this.dict.type.BGQX.length; j++) {
              if(response.rows[i].bgqx == this.dict.type.BGQX[j].value) {
                this.tableDataList[i].bgqx = this.dict.type.BGQX[j].label
              }
            }

            for (let j = 0; j < this.dict.type.IS_OPENS.length; j++) {
              if(response.rows[i].isOpens == this.dict.type.IS_OPENS[j].value) {
                this.tableDataList[i].isOpens = this.dict.type.IS_OPENS[j].label
              }
            }

            for (let j = 0; j < this.dict.type.WJLX.length; j++) {
              if(response.rows[i].wjlx == this.dict.type.WJLX[j].value) {
                this.tableDataList[i].wjlx = this.dict.type.WJLX[j].label
              }
            }
          }
          this.total = response.total
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      table_index(index){
        return (this.queryParams.pageNum-1) * this.queryParams.pageSize + index + 1;
      },
    }
  }
  </script>

  <style scoped>

  </style>
